//
//  BluetoothManager.swift
//  Nexs
//  蓝牙管理类，支持多设备连接
//  具体连接策略等配置可定义 BluetoothConfiguration
//
//  Created by roni on 2025/7/28.
//

import Foundation
import CoreBluetooth

// MARK: - 蓝牙管理器主类
public class BluetoothManager: NSObject {
    // MARK: - 公共属性
    
    /// 当前连接状态, 只代表最后连接设备的连接状态，不能以此判断有没有设备连接
    public weak var delegate: BluetoothManagerDelegate?
    
    /// 当前连接状态
    public private(set) var connectionState: BluetoothConnectionState = .idle {
        didSet {
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }
                self.delegate?.bluetoothManager(self, didChangeState: self.connectionState)
            }
        }
    }
    
    /// 当前连接的设备（仅为向后兼容，返回最后一个连接的设备）
    public var lastConnectedDevice: BluetoothDevice? {
        return connectedDevices.last?.device
    }
    
    /// 所有已连接的设备
    public private(set) var connectedDevices: [ConnectedBluetoothDevice] = []
    
    /// 蓝牙配置
    public private(set) var configuration: BluetoothConfiguration
    
    /// 是否正在扫描
    public var isScanning: Bool {
        return centralManager?.isScanning ?? false
    }
    
    /// 是否正在连接
    public var isConnecting: Bool {
        return connectingDevice != nil
    }
    
    /// 是否已连接（有任何设备连接即为true）
    public var isConnected: Bool {
        return !connectedDevices.isEmpty
    }
    
    /// 当前连接的设备数量
    public var connectedDeviceCount: Int {
        return connectedDevices.count
    }
    
    /// 是否可以连接更多设备
    public var canConnectMoreDevices: Bool {
        return connectedDevices.count < configuration.maxConcurrentConnections
    }
    
    /// 蓝牙是否可用
    public var isBluetoothAvailable: Bool {
        return centralManager?.state == .poweredOn
    }
    
    public var hasInitManager: Bool {
        centralManager != nil
    }
    
    // MARK: - 私有属性
    
    private var centralManager: CBCentralManager?
    private let blueQueue: DispatchQueue
    private var discoveredDevices: [BluetoothDevice] = []
    private var scanTimer: Timer?
    private var connectionTimer: Timer?
    
    // 回调闭包
    private var scanCompletion: BluetoothScanCompletion?
    private var connectionCompletion: BluetoothConnectionCompletion?
    private var serviceDiscoveryCompletion: BluetoothServiceDiscoveryCompletion?
    private var characteristicDiscoveryCompletion: BluetoothCharacteristicDiscoveryCompletion?
    private var readCompletion: BluetoothDataCompletion?
    private var writeCompletion: BluetoothWriteCompletion?
    private var readRSSICompletion: BluetoothReadRSSICompletion?
    
    // 连接中的设备
    private var connectingDevice: BluetoothDevice?
    
    private var logger: BluetoothLogable {
        return configuration.logger
    }
    
    // MARK: - 初始化
    
    public init(configuration: BluetoothConfiguration = BluetoothConfiguration()) {
        self.configuration = configuration
        self.blueQueue = DispatchQueue(label: configuration.identifier)
        super.init()
    }
    
    // MARK: - 公共方法
    // 要先创建
    func setupCentralManager() {
        guard centralManager == nil else {
            logger.log("centralManager 已经初始化过了")
            return
        }
        let options: [String: Any] = [CBCentralManagerOptionShowPowerAlertKey: false]
        centralManager = CBCentralManager(delegate: self, queue: blueQueue, options: options)
        logger.log("初始化 centralManager")
    }
    
    func resetCentralManager() {
        let options: [String: Any] = [CBCentralManagerOptionShowPowerAlertKey: false]
        centralManager = CBCentralManager(delegate: self, queue: blueQueue, options: options)
        logger.log("初始化 centralManager - reset")
    }
    
    /// 更新配置
    /// - Parameter configuration: 新的配置
    public func updateConfiguration(_ configuration: BluetoothConfiguration) {
        self.configuration = configuration
        logger.log("更新配置：\(configuration)")
    }
    
    /// 开始扫描设备
    /// - Parameter completion: 扫描完成回调
    public func startScanning(completion: BluetoothScanCompletion? = nil) {
        guard let centralManager = centralManager else {
            completion?(.failure(.bluetoothUnavailable))
            logger.log("蓝牙不可用，centralManager不存在")
            return
        }
        
        guard centralManager.state == .poweredOn else {
            completion?(.failure(.powerOff))
            logger.log("蓝牙不可用，蓝牙开关未开")
            return
        }
        
        guard !isScanning else {
            completion?(.success(discoveredDevices))
            logger.log("蓝牙不可用，正在扫描中")
            return
        }
        
        guard connectionState != .connecting else {
            completion?(.success(discoveredDevices))
            logger.log("不可连接，有设备连接中")
            return
        }
        
        // 重置发现的设备列表
        discoveredDevices.removeAll()
        scanCompletion = completion
        connectionState = .scanning
        
        logger.log("开始扫描， serviceUUIDs：\(String(describing: configuration.serviceUUIDs)), allowDuplicates: \(configuration.allowDuplicates)")
        
        // 开始扫描
        centralManager.scanForPeripherals(
            withServices: configuration.serviceUUIDs,
            options: [
                CBCentralManagerScanOptionAllowDuplicatesKey: configuration.allowDuplicates]
        )
        
        if configuration.scanTimeout > 0 {
            DispatchQueue.main.async {
                // 设置扫描超时
                self.scanTimer = Timer.scheduledTimer(withTimeInterval: self.configuration.scanTimeout, repeats: false) { [weak self] _ in
                    self?.stopScanning()
                    self?.scanCompletion?(.success(self?.discoveredDevices ?? []))
                    self?.scanCompletion = nil
                    self?.logger.log("扫描超时")
                }
            }
        }
    }
    
    /// 停止扫描
    public func stopScanning() {
        centralManager?.stopScan()
        scanTimer?.invalidate()
        scanTimer = nil
        
        if connectionState == .scanning {
            connectionState = .idle
        }
        logger.log("扫描停止")
    }
    
    /// 扫描并连接设备
    /// - Parameter completion: 连接完成回调
    public func scanAndConnect(completion: BluetoothConnectionCompletion? = nil) {
        logger.log("开始扫描+连接")
        self.connectionCompletion = completion
        startScanning { [weak self] result in
            guard let self = self else { return }
            
            switch result {
            case .success(let devices):
                guard !devices.isEmpty else {
                    completion?(.failure(.noDeviceFound))
                    return
                }
                
                logger.log("开始选择设备")
                // 根据策略选择设备
                let deviceToConnect = self.selectDeviceForConnection(from: devices)
                guard let device = deviceToConnect else {
                    completion?(.failure(.noDeviceFound))
                    return
                }
                
                logger.log("开始连接设备")
                self.connect(to: device, completion: completion)
                
            case .failure(let error):
                completion?(.failure(error))
            }
        }
    }
    
    /// 连接到指定设备
    /// - Parameters:
    ///   - device: 要连接的设备
    ///   - completion: 连接完成回调
    public func connect(to device: BluetoothDevice, completion: BluetoothConnectionCompletion? = nil) {
        guard let centralManager = centralManager else {
            completion?(.failure(.bluetoothUnavailable))
            logger.log("蓝牙不可用，centralManager不存在")
            return
        }
        
        guard centralManager.state == .poweredOn else {
            completion?(.failure(.powerOff))
            logger.log("蓝牙不可用，蓝牙开关为打开")
            return
        }
        
        // 检查是否已经连接
        if connectedDevices.contains(where: { $0.device.peripheral.identifier == device.peripheral.identifier }) {
            completion?(.failure(.alreadyConnected))
            logger.log("此设备已连接，identifier: \(device.peripheral.identifier)")
            return
        }
        
        // 检查是否已达到最大连接数
        guard canConnectMoreDevices else {
            completion?(.failure(.maxConnectionsReached))
            logger.log("已达最大连接数")
            return
        }
        
        // 检查是否正在连接
        if let connectingDevice = connectingDevice, connectingDevice.peripheral.identifier == device.peripheral.identifier {
            completion?(.failure(.alreadyConnected))
            logger.log("此设备已连接，identifier: \(device.peripheral.identifier)")
            return
        }
        
        // 添加到连接中的设备列表
        device.updateConnectionState(state: .connecting)
        connectingDevice = device
        connectionCompletion = completion
        connectionState = .connecting
        
        logger.log("正式开始连接")
        
        // 开始连接
        centralManager.connect(device.peripheral, options: nil)
        
        if configuration.connectionTimeout > 0 {
            // 设置连接超时
            DispatchQueue.main.async {
                self.connectionTimer = Timer.scheduledTimer(withTimeInterval: self.configuration.connectionTimeout, repeats: false) { [weak self] _ in
                    guard let self else {
                        return
                    }
                    self.logger.log("连接超时，timeout: \(self.configuration.connectionTimeout), identifier: \(device.peripheral.identifier)")
                    self.handleConnectionTimeout(for: device.peripheral.identifier)
                }
            }
        }
    }
    
    /// 断开连接（断开第一个连接的设备，为向后兼容）
    public func disconnectLast() {
        guard let device = lastConnectedDevice else { return }
        logger.log("断开设备连接，identifier: \(device.peripheral.identifier)")
        disconnect(device: device.peripheral.identifier)
    }
    
    /// 断开指定设备的连接
    /// - Parameter deviceId: 设备ID
    public func disconnect(device deviceId: UUID) {
        guard let connectedDevice = connectedDevices.first(where: { $0.device.peripheral.identifier == deviceId }) else { return }
        logger.log("断开指定设备连接，identifier: \(deviceId)")
        centralManager?.cancelPeripheralConnection(connectedDevice.device.peripheral)
    }
    
    /// 断开所有设备连接
    public func disconnectAll() {
        logger.log("断开所有设备")
        for connectedDevice in connectedDevices {
            centralManager?.cancelPeripheralConnection(connectedDevice.device.peripheral)
        }
    }
    
    /// 取消连接
    public func cancelConnection() {
        logger.log("取消设备连接")
        
        connectionTimer?.invalidate()
        connectionTimer = nil
        
        if let device = connectingDevice {
            centralManager?.cancelPeripheralConnection(device.peripheral)
        }
        
        connectionState = .idle
        connectingDevice = nil
    }
    
    // MARK: - 私有方法
    
    private func selectDeviceForConnection(from devices: [BluetoothDevice]) -> BluetoothDevice? {
        // 过滤掉已连接的设备
        let availableDevices = devices.filter { device in
            !connectedDevices.contains(where: { $0.device.peripheral.identifier == device.peripheral.identifier })
        }
        
        logger.log("选择一个设备，可用设备 count: \(availableDevices.count)")
        
        switch configuration.connectionStrategy {
        case .first:
            return availableDevices.first
        case .last:
            return availableDevices.last
        case .custom(let selector):
            return availableDevices.first(where: selector)
        case .connectWhenDiscovery(let selector):
            return availableDevices.first(where: selector)
        }
    }
    
    private func handleConnectionTimeout(for deviceId: UUID) {
        // 清理连接超时的设备
        connectionTimer?.invalidate()
        connectionTimer = nil
        
        // 如果是向后兼容的连接，触发旧的回调
        if let deviceToConnect = connectingDevice, deviceToConnect.peripheral.identifier == deviceId {
            connectionCompletion?(.failure(.connectionTimeout))
            connectionCompletion = nil
            self.connectingDevice = nil
        }
    }
    
    private func addConnectedDevice(_ device: BluetoothDevice) {
        let connectedDevice = ConnectedBluetoothDevice(device: device, connectionState: .connected)
        connectedDevices.append(connectedDevice)
        
        // 通知代理设备列表更新
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            self.delegate?.bluetoothManager(self, didUpdateConnectedDevices: self.connectedDevices)
        }
    }
    
    private func removeConnectedDevice(with deviceId: UUID) {
        connectedDevices.removeAll { $0.device.peripheral.identifier == deviceId }
        
        // 通知代理设备列表更新
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            self.delegate?.bluetoothManager(self, didUpdateConnectedDevices: self.connectedDevices)
        }
    }
    
    private func cleanupTimers() {
        logger.log("清理计时器")
        
        scanTimer?.invalidate()
        scanTimer = nil
        connectionTimer?.invalidate()
        connectionTimer = nil
    }
    
    /// 处理蓝牙状态变化
    /// - Parameters:
    ///   - newState: 新的连接状态
    ///   - message: 状态变化消息
    private func handleBluetoothStateChange(_ newState: BluetoothConnectionState, message: String) {
        logger.log("蓝牙状态变化: \(message)")
        
        if connectionState != newState {
            connectionState = newState
        }
        
        // 通知代理蓝牙中央管理器状态变化
        if let centralManager = centralManager {
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }
                self.delegate?.bluetoothManager(self, didChangeCentralState: centralManager.state, message: message)
            }
        }
    }
    
    /// 清理所有连接和状态
    private func cleanupAllConnections() {
        // 清理定时器
        cleanupTimers()
        
        // 断开所有已连接的设备
        let currentConnectedDevices = connectedDevices
        connectedDevices.removeAll()
        
        // 通知代理设备列表已清空
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            self.delegate?.bluetoothManager(self, didUpdateConnectedDevices: self.connectedDevices)
            
            // 通知每个设备的断开
            for connectedDevice in currentConnectedDevices {
                self.delegate?.bluetoothManager(self, didDisconnectFromDevice: connectedDevice.device, error: nil)
            }
        }
        
        // 重置向后兼容相关的状态
        connectingDevice = nil
        connectionCompletion = nil
        scanCompletion = nil
        serviceDiscoveryCompletion = nil
        characteristicDiscoveryCompletion = nil
        readCompletion = nil
        writeCompletion = nil
    }
    
    /// 尝试自动重连之前连接的设备
    private func attemptAutoReconnect() {
        // 这里可以实现自动重连逻辑
        // 例如：保存之前连接过的设备信息，在蓝牙重新可用时尝试重连
        logger.log("蓝牙已恢复，开始尝试自动重连...")
        
        // 注意：实际的自动重连实现需要：
        // 1. 在设备连接成功时保存设备信息到持久化存储
        // 2. 在这里读取保存的设备信息
        // 3. 尝试重新连接这些设备
        // 4. 处理重连成功和失败的情况
        
        // 示例实现（需要根据实际需求调整）：
        // if let savedDeviceIdentifiers = loadSavedDeviceIdentifiers() {
        //     for identifier in savedDeviceIdentifiers {
        //         attemptReconnectToDevice(with: identifier)
        //     }
        // }
    }
}

// MARK: - 连接之后的操作方法
extension BluetoothManager {
    /// 为指定设备发现服务
    /// - Parameters:
    ///   - serviceUUIDs: 要发现的服务UUID列表，nil表示发现所有服务
    ///   - deviceId: 设备ID
    ///   - completion: 发现完成回调
    public func discoverServices(_ serviceUUIDs: [String]? = nil, for deviceId: UUID, completion: BluetoothServiceDiscoveryCompletion? = nil) {
        guard let connectedDevice = connectedDevices.first(where: { $0.device.peripheral.identifier == deviceId }) else {
            completion?(.failure(.deviceNotFound))
            return
        }

        serviceDiscoveryCompletion = completion
        let uuids = serviceUUIDs?.map { CBUUID(string: $0) }
        logger.log("发现设备服务，deviceId：\(deviceId), uuids: \(String(describing: uuids))")
        connectedDevice.device.peripheral.discoverServices(uuids)
    }
    
    /// 为指定设备发现特征值
    /// - Parameters:
    ///   - characteristicUUIDs: 要发现的特征值UUID列表，nil表示发现所有特征值
    ///   - service: 目标服务
    ///   - deviceId: 设备ID
    ///   - completion: 发现完成回调
    public func discoverCharacteristics(_ characteristicUUIDs: [String]? = nil, for service: CBService, deviceId: UUID, completion: BluetoothCharacteristicDiscoveryCompletion? = nil) {
        guard let connectedDevice = connectedDevices.first(where: { $0.device.peripheral.identifier == deviceId }) else {
            completion?(.failure(.deviceNotFound))
            return
        }
        
        logger.log("发现设备特征值， device: \(deviceId)")
        characteristicDiscoveryCompletion = completion
        let uuids = characteristicUUIDs?.map { CBUUID(string: $0) }
        connectedDevice.device.peripheral.discoverCharacteristics(uuids, for: service)
    }
    
    /// 读取指定设备的特征值数据
    /// - Parameters:
    ///   - characteristic: 要读取的特征值
    ///   - deviceId: 设备ID
    ///   - completion: 读取完成回调
    public func readValue(for characteristic: CBCharacteristic, deviceId: UUID, completion: BluetoothDataCompletion? = nil) {
        guard let connectedDevice = connectedDevices.first(where: { $0.device.peripheral.identifier == deviceId }) else {
            completion?(.failure(.deviceNotFound), nil)
            return
        }
        
        logger.log("读取设备特征值， device: \(deviceId)")
        readCompletion = completion
        connectedDevice.device.peripheral.readValue(for: characteristic)
    }
    
    /// 写入数据到指定设备的特征值
    /// - Parameters:
    ///   - data: 要写入的数据
    ///   - characteristic: 目标特征值
    ///   - deviceId: 设备ID
    ///   - type: 写入类型
    ///   - completion: 写入完成回调
    public func writeValue(_ data: Data, for characteristic: CBCharacteristic, deviceId: UUID, type: CBCharacteristicWriteType = .withResponse, completion: BluetoothWriteCompletion? = nil) {
        guard let connectedDevice = connectedDevices.first(where: { $0.device.peripheral.identifier == deviceId }) else {
            completion?(.failure(.deviceNotFound))
            return
        }
        
        logger.log("写数据， device: \(deviceId)，withResponse：\(type == .withResponse)")
        writeCompletion = completion
        connectedDevice.device.peripheral.writeValue(data, for: characteristic, type: type)
        
        // 如果是无响应写入，立即调用完成回调
        if type == .withoutResponse {
            completion?(.success(()))
            writeCompletion = nil
        }
    }
    
    /// 设置指定设备的特征值通知
    /// - Parameters:
    ///   - enabled: 是否启用通知
    ///   - characteristic: 目标特征值
    ///   - deviceId: 设备ID
    public func setNotifyValue(_ enabled: Bool, for characteristic: CBCharacteristic, deviceId: UUID) {
        guard let connectedDevice = connectedDevices.first(where: { $0.device.peripheral.identifier == deviceId }) else { return }
        
        logger.log("订阅设备特征值,characteristic: \(characteristic.uuid.uuidString)，device: \(deviceId)")
        connectedDevice.device.peripheral.setNotifyValue(enabled, for: characteristic)
    }
    
    /// 读取指定设备的RSSI
    /// - Parameters:
    ///   - characteristic: 要读取的特征值
    ///   - deviceId: 设备ID
    ///   - completion: 读取完成回调
    public func readRSSI(deviceId: UUID, completion: BluetoothReadRSSICompletion? = nil) {
        guard let connectedDevice = connectedDevices.first(where: { $0.device.peripheral.identifier == deviceId }) else {
            completion?(.failure(.deviceNotFound))
            return
        }
        
        logger.log("读取设备RSSI， device: \(deviceId)")
        readRSSICompletion = completion
        connectedDevice.device.peripheral.readRSSI()
    }
}

// MARK: - CBCentralManagerDelegate
extension BluetoothManager: CBCentralManagerDelegate {
    
    public func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .unknown:
            // 蓝牙状态未知，通常是初始化状态
            handleBluetoothStateChange(.idle, message: "蓝牙状态未知")
        case .resetting:
            // 蓝牙系统正在重置
            handleBluetoothStateChange(.idle, message: "蓝牙系统重置中")
            cleanupAllConnections()
        case .unsupported:
            // 设备不支持蓝牙
            handleBluetoothStateChange(.idle, message: "设备不支持蓝牙")
            cleanupAllConnections()
        case .unauthorized:
            // 应用未获得蓝牙使用授权
            handleBluetoothStateChange(.idle, message: "蓝牙访问未授权，请检查设置")
            cleanupAllConnections()
        case .poweredOff:
            // 蓝牙已关闭
            handleBluetoothStateChange(.idle, message: "蓝牙已关闭，请开启蓝牙")
            cleanupAllConnections()
        case .poweredOn:
            // 蓝牙已开启，可以开始扫描和连接
            handleBluetoothStateChange(.idle, message: "蓝牙已开启")
            // 如果启用了自动重连，可以在这里尝试重连之前的设备
            if configuration.autoReconnect {
                attemptAutoReconnect()
            }
        @unknown default:
            // 处理未来可能新增的状态
            handleBluetoothStateChange(.idle, message: "未知的蓝牙状态: \(central.state.rawValue)")
            cleanupAllConnections()
        }
    }
    
    public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber) {
        // 回调设备
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            self.delegate?.bluetoothManager(self, didDiscover: peripheral, advertisementData: advertisementData, rssi: RSSI)
        }
        
        // 根据自定义规则过滤设备
        if let filter = configuration.filter {
            if !filter(peripheral, advertisementData, RSSI) {
                return
            }
        }
        
        let device = BluetoothDevice(peripheral: peripheral, advertisementData: advertisementData, rssi: RSSI)
        
        // 避免重复添加相同设备
        if !discoveredDevices.contains(where: { $0.peripheral.identifier == peripheral.identifier }) {
            discoveredDevices.append(device)
            logger.log("发现新设备, device: \(peripheral.identifier), name: \(String(describing: peripheral.name))")
            
            DispatchQueue.main.async { [weak self] in
                guard let self = self else { return }
                self.delegate?.bluetoothManager(self, didDiscoverDevice: device)
            }
            
            switch configuration.connectionStrategy {
            case .connectWhenDiscovery(let handler):
                // 检查是否已经连接
                if connectedDevices.contains(where: { $0.device.peripheral.identifier == device.peripheral.identifier }) {
                    logger.log("发现新设备， 但此设备已连接，identifier: \(device.peripheral.identifier)")
                    return
                }
                
                if handler(device) {
                    logger.log("立刻开始连接")
                    stopScanning()
                    connect(to: device, completion: self.connectionCompletion)
                }
            default:
                break
            }
        }
    }
    
    public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        // 清理该设备的连接定时器
        connectionTimer?.invalidate()
        connectionTimer = nil

        guard let device = connectingDevice else {
            return
        }
        
        logger.log("连接新设备成功, device: \(peripheral.identifier)")
        
        // 设置外设代理
        device.peripheral.delegate = self
        
        // 添加到已连接设备列表
        device.deviceServicesMapArray = configuration.deviceServicesMapArray
        addConnectedDevice(device)
        
        // 为向后兼容处理
        if let deviceToConnect = connectingDevice, deviceToConnect.peripheral.identifier == peripheral.identifier {
            connectionState = .connected
            connectionCompletion?(.success(device))
            connectionCompletion = nil
            self.connectingDevice = nil
        }
        
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            self.delegate?.bluetoothManager(self, didConnectToDevice: device)
        }
        
        // 发现服务, 为空则返回 nil
        let serviceIds = device.serviceIds.isEmpty ? nil : device.serviceIds
        discoverServices(serviceIds, for: peripheral.identifier)
    }
    
    public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        logger.log("连接新设备失败, device: \(peripheral.identifier)")
        
        // 清理该设备的连接定时器
        connectionTimer?.invalidate()
        connectionTimer = nil
        
        let device = connectingDevice
        
        // 为向后兼容处理
        if let deviceToConnect = connectingDevice, deviceToConnect.peripheral.identifier == peripheral.identifier {
            connectionState = .failed
            connectionCompletion?(.failure(.connectionFailed(error)))
            connectionCompletion = nil
            self.connectingDevice = nil
        }
        
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            self.delegate?.bluetoothManager(self, didFailToConnect: device, error: .connectionFailed(error))
        }
    }
    
    public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        // 查找断开连接的设备
        guard let connectedDevice = connectedDevices.first(where: { $0.device.peripheral.identifier == peripheral.identifier }) else { return }
        
        logger.log("设备断连, device: \(peripheral.identifier)")
        
        let device = connectedDevice.device
        
        // 从已连接设备列表中移除
        removeConnectedDevice(with: peripheral.identifier)
        
        // 为向后兼容处理
        if connectedDevices.isEmpty {
            connectionState = .disconnected
        }
        
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            self.delegate?.bluetoothManager(self, didDisconnectFromDevice: device, error: error)
        }
    }
}

// MARK: - CBPeripheralDelegate
extension BluetoothManager: CBPeripheralDelegate {
    
    public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        if let error = error {
            serviceDiscoveryCompletion?(.failure(.connectionFailed(error)))
            serviceDiscoveryCompletion = nil
            return
        }
        
        guard let connectedDevice = connectedDevices.first(where: { $0.device.peripheral.identifier == peripheral.identifier }) else {
            return
        }
        
        let services = peripheral.services ?? []
        
        serviceDiscoveryCompletion?(.success(services))
        serviceDiscoveryCompletion = nil
        // event - 发现特征值
        if error == nil, !services.isEmpty {
            for service in services {
                let characteristics = connectedDevice.device.getCharacteristicIdsInService(service.uuid.uuidString)
                discoverCharacteristics(characteristics, for: service, deviceId: peripheral.identifier)
            }
        }
    }
    
    public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        if let error = error {
            characteristicDiscoveryCompletion?(.failure(.connectionFailed(error)))
            characteristicDiscoveryCompletion = nil
            return
        }
        
        let characteristics = service.characteristics ?? []
        
        characteristicDiscoveryCompletion?(.success(characteristics))
        characteristicDiscoveryCompletion = nil
        
        logger.log("serviceId: \(service.uuid.uuidString)")
        
        // event - 订阅特征值，由外界实现的代理方法实现
        if error == nil, !characteristics.isEmpty {
            // 保存特征值
            let connectedDevice = connectedDevices.first(where: { $0.device.peripheral.identifier == peripheral.identifier })
            connectedDevice?.device.addCharacteristics(characteristics)
            
            for characteristic in characteristics {
                logger.log("characteristic: \(characteristic.uuid.uuidString)")
                // 发现特征值描述 - 目前设备不需要，不用发现，节省电量
//                peripheral.discoverDescriptors(for: characteristic)
                
                if characteristic.properties.contains(CBCharacteristicProperties.notify) {
                    // 订阅特征值
                    logger.log("订阅-characteristic: \(characteristic.uuid.uuidString)")
                    setNotifyValue(true, for: characteristic, deviceId: peripheral.identifier)
                }
            }
        }
    }
    
    public func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: (any Error)?) {
        logger.log("订阅-characteristic: \(characteristic.uuid.uuidString), 是否成功：\(error == nil)")
        let connectedDevice = connectedDevices.first(where: { $0.device.peripheral.identifier == peripheral.identifier })
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            self.delegate?.bluetoothManager(self, didSubscribeCharacteristics: characteristic, device: connectedDevice?.device, isSuccess: error == nil)
        }
    }
    
    public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        if let error = error {
            readCompletion?(.failure(.readError(error)), nil)
            readCompletion = nil
            return
        }
        
        guard let data = characteristic.value else {
            readCompletion?(.failure(.readError(nil)), nil)
            readCompletion = nil
            return
        }
        
        guard let connectedDevice = connectedDevices.first(where: { $0.device.peripheral.identifier == peripheral.identifier }) else {
            let idsString = connectedDevices.map { $0.device.deviceId.uuidString }.joined(separator: ",")
            logger.log("didUpdateValueFor：收到特征值更新，但是未找到设备， identifier：\( peripheral.identifier), connectedDevices: \(idsString)")
            return
        }
        
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            self.delegate?.bluetoothManager(self, didReceiveData: data, from: connectedDevice.device, on: characteristic)
        }
        
        readCompletion?(.success(data), characteristic)
        readCompletion = nil
    }
    
    public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
        let connectedDevice = connectedDevices.first(where: { $0.device.peripheral.identifier == peripheral.identifier })
        
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            self.delegate?.bluetoothManager(self, didWriteValueFor: characteristic, device: connectedDevice?.device, error: error)
        }
        
        if let error = error {
            writeCompletion?(.failure(.writeError(error)))
        } else {
            writeCompletion?(.success(()))
        }
        writeCompletion = nil
    }
    
    public func peripheral(_ peripheral: CBPeripheral, didReadRSSI RSSI: NSNumber, error: (any Error)?) {
        if let error = error {
            readRSSICompletion?(.failure(.readRSSIError(error)))
        } else {
            readRSSICompletion?(.success(RSSI))
        }
        readRSSICompletion = nil
    }
    
    public func peripheral(_ peripheral: CBPeripheral, didDiscoverDescriptorsFor characteristic: CBCharacteristic, error: (any Error)?) {
        // 不实现
    }
}
